var express = require('express');
var router = express.Router();

var md5 = require('MD5');


var dbConfig = require("../db_connection/dbConfig");
var connection = dbConfig.getConnection();

/* GET home page. */
router.get('/:company/login', function(req, res) {
	exports.validateCompany(req, res, function(){
		res.render('login', {
			company: req.param("company"),
			msg : "",
			username : ""
		});
	});
});



router.post('/:company/login', function(req, res) {
	
	exports.validateCompany(req, res, function(retrivedCompanyId){
		var username = {username : req.param("username") } ;
		
		var companyId = {company_id : retrivedCompanyId } ;
		
		var passwordMD5 = md5(req.param("password") );
		
		var password = {password : passwordMD5 } ;
		
		
		var query = connection.query("SELECT * FROM user WHERE ? and ? and ? limit 1" , [username, password, companyId] , function(err, userRows)
				{
					console.log("LOGIN QUERY : " + query.sql);
					console.log("LENGTH == > " + userRows.length );
	                if(userRows.length > 0 && userRows[0]["user_group_id"] != null){
						var userGroupQuery = connection.query("SELECT * FROM user_group where id = ?" , [userRows[0]["user_group_id"]] , function(err, userGroupRows)
						{
							if(userGroupRows.length > 0 && userGroupRows[0]["id"] != null){
								var group = userGroupRows[0];
									res.cookie('USER_ID', userRows[0]["id"]);
									res.cookie('USER_NAME', userRows[0]["username"]);
									res.cookie('USER_FULLNAME', userRows[0]["firstname"] + " " + userRows[0]["lastname"]);
									res.cookie('USER_GROUP_ID', group["id"]);
									res.cookie('USER_GROUP_NAME', group["name"]);
									res.cookie('BRANCH_ID', userRows[0]["branch_id"]);
									res.cookie('COMPANY_KEY', req.param("company"));
									res.redirect("/"+ req.param("company") + "/backend");
							}
						});
	                }else{
	                	res.render('login', {
	                		msg : "Invalid Username or Password.",
	                		company: req.param("company"),
	                		username :  req.param("username")
	                		//password :  req.param("password"),
	                	});
	                }
					
				});
	});
});


module.exports.validateCompany = function(req, res, callback){
	var companyCondition = { key : req.param("company")}
	var companyQuery = connection.query("SELECT id FROM company WHERE ? and archived = 1 limit 1" , [companyCondition] , function(err, companyRow)
		{
			console.log("SQL == >> " + companyQuery.sql);
			var errorFunction  = function(){
				res.render('login', {
            		msg : "COMPANY NOT FOUND",
            		company: req.param("company"),
            		username :  req.param("sample")
            		//password :  req.param("password"),
            	});
			}
			console.log(111111);
			if(err){
				console.log(22222);
				errorFunction();
			}else{
				if(typeof companyRow !== "undefined" && companyRow.length == 1 ){
					console.log(33333);
					callback(companyRow[0]["id"]);
				}else{
					console.log(4444);
					errorFunction();
				}
			}
		}
	);
}


/* GET home page. */
router.get('/sample', function(req, res) {
	console.log("Qwe");
	res.render('index', { title: 'Express-sample' });
});

module.exports = router;
